<template>
  <div>
    <div id="components-form-demo-advanced-search">
      <a-row :gutter="24" style="margin-bottom: 15px">
        <a-col :span="6">
          账单编号：<a-input
          :maxLength="128"
            v-model="searchData.billNumber"
            style="width: 60%"
          />
        </a-col>
        <a-col :span="6">
          账单渠道：
          <a-input
          :maxLength="128"
            v-model="searchData.channel"
            style="width: 60%"
          />
        </a-col>
        <a-col :span="6">
          物流平台：
          <a-select
            style="width: 60%"
            v-model="searchData.platform"
            show-search
            option-filter-prop="children"
            :filter-option="filterOption"
          >
            <a-select-option
              v-for="(item, i) in LogisticsPlatform"
              :value="item.logisticsPlatform"
              :key="i"
              :logisticsPlatform="item.logisticsPlatform"
              :serviceName="item.serviceName"
              :sysLogisticsId="item.sysLogisticsId"
              :sysLogisticsServiceItemId="item.sysLogisticsServiceItemId"
            >
              {{ item.logisticsPlatform }}
            </a-select-option>
          </a-select>
        </a-col>
        <a-col :span="6">
          <div v-show="!expand">
            <a-button
              type="primary"
              class="searchBtn"
              @click="
                () => {
                  getTableList();
                }
              "
            >
              查询
            </a-button>
            <a-button
              style="margin: 0 10px"
              type="primary"
              class="searchBtn"
              @click="resetSearch"
            >
              重置
            </a-button>
            <a
              :style="{ marginRight: '8px', fontSize: '14px' }"
              @click="expand = !expand"
            >
              {{ expand ? "折叠" : "展开" }}
              <a-icon :type="expand ? 'up' : 'down'" />
            </a>
          </div>
          <div v-show="expand">
            时间范围：<a-range-picker
              v-model="searchTime"
              @change="onStorageTimeChange"
              style="width: 60%"
            />
          </div>
        </a-col>
      </a-row>
      <a-row :gutter="24" v-show="expand">
        <a-col :span="6">
          <div v-show="expand">
            <a-button
              type="primary"
              class="searchBtn"
              @click="
                () => {
                  getTableList();
                }
              "
            >
              查询
            </a-button>
            <a-button
              style="margin: 0 10px"
              type="primary"
              class="searchBtn"
              @click="resetSearch"
            >
              重置
            </a-button>
            <a
              :style="{ marginRight: '8px', fontSize: '14px' }"
              @click="expand = !expand"
            >
              {{ expand ? "折叠" : "展开" }}
              <a-icon :type="expand ? 'up' : 'down'" />
            </a>
          </div>
        </a-col>
        <a-col :span="6"> </a-col>
        <a-col :span="6"> </a-col>
        <a-col :span="6"> </a-col>
      </a-row>
    </div>
    <div style="margin-top: 20px">
      <a-button type="primary" class="top-btn frebtn" @click="importFile">
        导入
      </a-button>
    </div>
    <a-spin tip="Loading..." :spinning="spinning">
      <a-table
        :columns="columns"
        :scroll="{ x: 1500 }"
        :data-source="tableData"
        :pagination="false"
      >
        <span slot="remark" slot-scope="texrt, record">
          <span>
            {{ record.remark }}
          </span>
          <a-input
          :maxLength="128"
            size="small"
            style="width: 30%"
            v-if="record.remarkFlag"
            v-model="remark"
          />
          <a-button
            size="small"
            v-if="
              !record.remarkFlag &&
              (record.remark == null || record.remark == '')
            "
            @click="record.remarkFlag = true"
            >编辑</a-button
          >
          <a-button
            size="small"
            v-if="record.remarkFlag"
            @click="savaRemark(record)"
            >保存</a-button
          >
          <a-button
            size="small"
            v-if="record.remarkFlag"
            @click="
              () => {
                record.remarkFlag = false;
                remark = '';
              }
            "
            >取消</a-button
          >
        </span>
        <span slot="billDate" slot-scope="texrt, record">
          {{ record.billDate.replaceAll("T", " ") }}
        </span>
        <span slot="updateTime" slot-scope="texrt, record">
          {{ record.updateTime.replaceAll("T", " ") }}
        </span>
        <span slot="action" slot-scope="text, record">
          <a
            href="javascript:;"
            style="text-decoration: underline; color: rgb(41, 41, 224)"
            @click="exportExcelRow(record)"
            >导出结果
          </a>
          <a-divider type="vertical" />
          <a
            href="javascript:;"
            style="text-decoration: underline; color: rgb(41, 41, 224)"
            @click="rowServiceInfo(record)"
            >账单详情
          </a>
        </span>
      </a-table>
    </a-spin>
    <!-- 分页器 -->
    <div style="margin: 20px 0; text-align: center">
      <a-config-provider>
        <a-pagination
          :current="searchData.current"
          show-size-changer
          :pageSizeOptions="['10', '20', '30']"
          :show-total="
            (total) => `${$t('m.page.Total')} ${total} ${$t('m.page.items')}`
          "
          @showSizeChange="showChange"
          :buildOptionText="
            (props) => ` ${props.value} ${$t('m.page.a')}/${$t('m.page.page')}`
          "
          show-quick-jumper
          :default-current="searchData.current"
          :total="total"
          @change="onChangePage"
        />
      </a-config-provider>
    </div>

    <!-- //导入文件 -->
    <a-modal v-model="importFileVisible" title="导入">
      <template slot="footer">
        <a-button @click="importFileVisible = false">关闭</a-button>
        <a-button type="primary" @click="importAffirm" :loading="loading">
          确认
        </a-button>
      </template>
      <a-form-model
        ref="importFileForm"
        :model="importFileForm"
        :rules="importFileRules"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
      >
        <a-form-model-item label="账单类型" prop="billType">
          <a-select
            v-model="importFileForm.billType"
            show-search
            option-filter-prop="children"
            :filter-option="filterOption"
            @change="handleChangeLogistics"
          >
            <a-select-option
              v-for="(item, i) in logisticsArr"
              :value="
                item.sysLogisticsId + ',' + item.sysLogisticsServiceItemId
              "
              :key="i"
              :logisticsPlatform="item.logisticsPlatform"
              :serviceName="item.serviceName"
              :sysLogisticsId="item.sysLogisticsId"
              :sysLogisticsServiceItemId="item.sysLogisticsServiceItemId"
            >
              <a-tooltip>
                <template slot="title">
                  {{ item.serviceName }}/{{ item.logisticsPlatform }}
                </template>
                {{ item.serviceName }}/{{ item.logisticsPlatform }}
              </a-tooltip>
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="账单币种" prop="billCurrency">
          <a-select
            style="width: 100%"
            show-search
            option-filter-prop="children"
            allowClear
            v-model="importFileForm.billCurrency"
          >
            <a-select-option
              :name="item.currency"
              :value="item.currency"
              v-for="item in settlementCurrencys"
              :key="item.sysCurrencyId"
            >
              {{ item.currency }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="换算币种" prop="convertCurrency">
          <a-select
            style="width: 100%"
            show-search
            option-filter-prop="children"
            allowClear
            v-model="importFileForm.convertCurrency"
          >
            <a-select-option
              :name="item.currency"
              :value="item.currency"
              v-for="item in settlementCurrencys"
              :key="item.sysCurrencyId"
            >
              {{ item.currency }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="换算汇率" prop="convertRate">
          <a-input-number
            v-model="importFileForm.convertRate"
            :precision="2"
            :min="0"
          />
        </a-form-model-item>
        <a-form-model-item label="选择文件" prop="file">
          <a-upload
            name="file"
            :multiple="true"
            :remove="handleRemove"
            :beforeUpload="beforeUploads"
            :file-list="fileList"
          >
            <a-button v-if="fileList.length < 1">
              <a-icon type="upload" />上传文件
            </a-button>
          </a-upload>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>

<script>
import req from "@/utils/req";
import baseUrl from "@/utils/baseUrl";
import { logi_getCurrency } from "@/apis/system/setManage/setWarehouse";
import { selectAllLogistics } from "@/apis/common";
import {
  WaybillCheck_pageWaybillMaster,
  WaybillCheck_pageWaybillMasterRemark,
  WaybillCheck_pageWaybillUpLoad,
  WaybillCheck_exportExcel,
} from "@/apis/system/FinanceManagement/FinanceManagement";
export default {
  created() {
    this.getLogistics();
    this.getTableList();
    this.getCurrency();
  },
  data() {
    return {
      loading: false,
      baseUrl,
      //上传文件请求头
      headers: {
        authorization: "authorization-text",
        token: sessionStorage.getItem("tk"),
      },
      //已经上传文件列表
      fileList: [],
      importFileForm: {
        billType: "",
        billCurrency: "",
        convertCurrency: "",
        convertRate: "",
        file: "",
        fileName: "",
        billTypeId: "",
      },
      importFileRules: {
        billType: [
          { required: true, message: "请选择账单类型！", trigger: "change" },
        ],
        billCurrency: [
          { required: true, message: "请选择账单币种！", trigger: "change" },
        ],
        file: [{ required: true, message: "请上传文件！", trigger: "change" }],
      },
      labelCol: { span: 6 },
      wrapperCol: { span: 14 },
      //导入文件模态框
      importFileVisible: false,
      searchTime: null,
      tableData: [],
      total: 1,
      expand: false,
      searchData: {
        size: 10,
        current: 1,
        billNumber: null,
        channel: null,
        platform: null,
        startDate: null,
        endtDate: null,
      },
      remark: "",
      //物流商数组
      logisticsArr: [],
      // 物流平台
      LogisticsPlatform: [],
      //币种
      settlementCurrencys: [],
    };
  },
  methods: {
    // 物流商更改
    async handleChangeLogistics(value, option) {
      this.importFileForm.billType =
        option.data.attrs.serviceName +
        "/" +
        option.data.attrs.logisticsPlatform;
      this.importFileForm.billTypeId = option.data.attrs.sysLogisticsId;
      "," + option.data.attrs.sysLogisticsServiceItemId;
    },
    //导出账单详情列表
    async exportExcelRow(record) {
      let res = await WaybillCheck_exportExcel(record.billNumber);
      req.exportFile("已核帐账单", res);
    },
    //导入确认
    importAffirm() {
      this.loading = true;
      const fromData = new FormData();
      this.fileList.forEach((file) => {
        fromData.append("file", file);
      });
      this.$refs.importFileForm.validate(async (valid) => {
        if (valid) {
          let { code } = await WaybillCheck_pageWaybillUpLoad(
            this.importFileForm.billType,
            this.importFileForm.billCurrency,
            this.importFileForm.convertCurrency,
            this.importFileForm.convertRate,
            fromData
          );
          if (code == "10000") {
            this.importFileVisible = false;
            this.loading = false;
            this.getTableList();
          } else {
            this.loading = false;
          }
        } else {
          this.loading = false;
          this.$message.error("请检查必填项！");
          return false;
        }
      });
    },

    //导入文件
    importFile() {
      if (this.$refs.importFileForm) {
        this.$refs.importFileForm.resetFields();
      }
      this.importFileVisible = true;
      this.importFileForm = {
        billType: "",
        billCurrency: "",
        convertCurrency: "",
        convertRate: "",
        file: "",
        fileName: "",
        billTypeId: "",
      };
      this.fileList = [];
    },
    //账单详情
    rowServiceInfo(record) {
      //   let res = await WaybillCheck_pageWaybillMasterRemarkInfo(
      //     record.billNumber,
      //     1,
      //     10
      //   );
      //   console.log(res);
      this.$emit("rowServiceInfo", record);
    },
    //保存每一行备注
    async savaRemark(record) {
      if ((this.remark ?? "") == "") {
        this.$message.error("请输入备注后保存!");
        return false;
      }
      let { code } = await WaybillCheck_pageWaybillMasterRemark(
        record.id,
        this.remark
      );
      if (code == "10000") {
        this.getTableList();
      }
    },
    // 限制上传文件
    beforeUploads(file) {
      let fileSuffix = file.name.split(".")[file.name.split(".").length - 1];
      this.files = file;
      let isLt100M = file.size / 1024 / 1024 < 100;
      fileSuffix = fileSuffix === "csv";
      if (!fileSuffix) {
        this.$message.error("上传文件只能是csv后缀!");
        return false;
      }
      if (!isLt100M) {
        this.$message.error("文件大小限制小于100MB!");
        return false;
      }
      if (isLt100M && fileSuffix) {
        this.importFileForm.file = 1;
        this.fileList = [...this.fileList, file];
        return false;
      }
    },
    //文件删除
    handleRemove(file) {
      const index = this.fileList.indexOf(file);
      const newFileList = this.fileList.slice();
      newFileList.splice(index, 1);
      this.fileList = newFileList;
      this.importFileForm.file = null;
    },
    //获取表格数据
    async getTableList() {
      this.spinning = true;
      let { code, responseBody } = await WaybillCheck_pageWaybillMaster(
        this.searchData
      );
      if (code == "200") {
        if (responseBody.records.length >= 1) {
          responseBody.records.forEach((item) => {
            item.remarkFlag = false;
          });
        }
        this.tableData = responseBody.records;
        this.total = responseBody.total * 1;
        this.spinning = false;
      }
    },
    //重置
    resetSearch() {
      this.searchTime = null;
      let current = this.searchData.current;
      let size = this.searchData.size;
      this.searchData = {
        size: size,
        current: current,
        billNumber: null,
        channel: null,
        platform: null,
        startDate: null,
        endtDate: null,
      };
      this.getTableList();
    },
    //结算时间
    onStorageTimeChange(date, dateString) {
      this.searchData.startDate = dateString[0];
      this.searchData.endtDate = dateString[1];
    },
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },
    //分页器事件
    onChangePage(pageNumber) {
      this.searchData.current = pageNumber;
      this.getTableList();
    },
    //页码变更
    showChange(size, current) {
      this.searchData.current = size;
      this.searchData.size = current;
      this.getTableList();
    },
    //获取物流商
    async getLogistics() {
      let { code, responseBody } = await selectAllLogistics();
      if (code === "200") {
        this.logisticsArr = responseBody;
        this.LogisticsPlatform = this.deWeightThree(responseBody);
      }
    },
    //获取币种的接口
    async getCurrency() {
      let res = await logi_getCurrency({ size: 100000, current: 1 });
      if (res.code == "200") {
        this.settlementCurrencys = res.responseBody.records;
      }
    },
    //数组对象去重
    deWeightThree(data) {
      let map = new Map();
      for (let item of data) {
        if (!map.has(item.logisticsPlatform)) {
          map.set(item.logisticsPlatform, item);
        }
      }
      return [...map.values()];
    },
  },
  computed: {
    columns() {
      return [
        {
          title: "账单编号",
          dataIndex: "billNumber",
          align: "center",
          scopedSlots: { customRender: "billNumber" },
          width: "16%",
          //  fixed: "left",
        },
        {
          title: "账单日期",
          dataIndex: "billDate",
          align: "center",
          scopedSlots: { customRender: "billDate" },
          width: "10%",
        },
        {
          title: "账单标题",
          dataIndex: "billTitle",
          align: "center",
          width: "10%",
        },
        {
          title: "账单渠道",
          dataIndex: "channel",
          // ellipsis: true,
          scopedSlots: { customRender: "channel" },
          align: "center",
          width: "10%",
        },
        {
          title: "账单供应商",
          dataIndex: "platform",
          scopedSlots: { customRender: "platform" },
          align: "center",
          width: "10%",

          // ellipsis: true,
        },
        {
          title: "账单总金额",
          dataIndex: "billAmount",
          scopedSlots: { customRender: "billAmount" },
          align: "center",
          width: "10%",

          // ellipsis: true,
        },
        {
          title: "已对账(笔数)",
          dataIndex: "waybillCount",
          scopedSlots: { customRender: "waybillCount" },
          align: "center",
          width: "10%",
        },

        {
          title: "无对账(笔数)",
          dataIndex: "waybillNoCount",
          scopedSlots: { customRender: "waybillNoCount" },
          align: "center",
          width: "10%",
        },
        {
          title: "导入时间",
          dataIndex: "updateTime",
          scopedSlots: { customRender: "updateTime" },
          align: "center",
          width: "10%",
        },
        {
          title: "备注 ",
          dataIndex: "remark",
          align: "center",
          scopedSlots: { customRender: "remark" },
          // ellipsis: true,
          width: "20%",
        },
        {
          title: "操作",
          dataIndex: "action",
          scopedSlots: { customRender: "action" },
          align: "center",
          fixed: "right",
          width: 200,
        },
      ];
    },
  },
};
</script>

<style lang="less" scoped>
.searchBtn {
  background: #fff;
  color: #3eae7c;
  text-shadow: none;
}
.searchBtn:hover {
  background: #3eae7c;
  color: #fff;
}
.top-btn:hover {
  background: #3eae7c;
  color: #fff;
}
.frebtn {
  background-color: #66b1ff;
  color: #fff;
  border: #66b1ff;
}
.frebtn:hover {
  background-color: #66b1ff;
  color: #fff;
  border: #66b1ff;
}
</style>